//
//  LoopUserAccountViewModel.swift
//  LoopWeibo
//
//  Created by loop安 on 2016/12/10.
//  Copyright © 2016年 loop. All rights reserved.
//

import UIKit

class LoopUserAccountViewModel: NSObject {

    //由于需要处理逻辑业务,所以需要模型数据
    var userAccount:LoopUserAccount?
    
    //创建单例对象,保证全局只有一个账号
    static let shared = LoopUserAccountViewModel()
    
    override init() {
        super.init()
        userAccount = loadUserInfo()
    }
    
    //声明变量判断是否登录
    var userLogin:Bool{
    //当令牌不为空且没有过期,表示已经登录
        if userAccount?.access_token != nil && isExpires == false{
        return true
        }
    return false
    }
    
    //声明变量,判断登录是否过期
    var isExpires:Bool{
    
        if userAccount?.expires_date?.compare(Date()) == .orderedDescending {
            return false
        }
        
    return true
    }
    
    var headUrl:URL?{
        return URL(string: LoopUserAccountViewModel.shared.userAccount?.avatar_large ?? "")
    }
    
    
    var access_token:String?{
        return userAccount?.access_token
    }
    
    func loadUserToken(code:String,finish:@escaping (Bool)->()){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : client_id,
                          "client_secret" : client_secret,
                          "grant_type" : "authorization_code",
                          "code" : code,
                          "redirect_uri" : redirect_uri]
        LoopNetWorkManager.shared.request(HTTPMethod: .POST, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil{
//                SVProgressHUD.showError(withStatus: errorTip)
                finish(false)
                return
            }
            //走到这里程序一定是成功的
            //            print(responseObject)
//            self.loadUserInfo(dic: responseObject as! [String : Any],finish)
            self.loadUserInfo(dic: responseObject as! [String : Any], userInfofinish: finish)
        }
    }
    
    private func loadUserInfo(dic:[String : Any],userInfofinish:@escaping (Bool)->()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let access_token = dic["access_token"]
        let uid = dic["uid"]
        let parameters = ["access_token" : access_token,
                          "uid" : uid]
        print(parameters)
        LoopNetWorkManager.shared.request(HTTPMethod: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil{
//                SVProgressHUD.showError(withStatus: errorTip)
                userInfofinish(false)
                return
            }
            //            print(responseObject)
            
            //将返回的数据转换成字典
            var userInfo = responseObject as! [String : Any]
            
            //由于access_token在传入的dic中,所以我们需要将两个字典合并
            for (key,value) in dic {
                userInfo[key] = value
            }
            
            //归档,将数据存储到本地
            //创建模型数据
            let userAccount = LoopUserAccount(dic: userInfo)
            
            self.saveUserInfo(userAccount: userAccount)
            
            self.userAccount = userAccount
            
            userInfofinish(true)
        }
        
    }
    
    //归档方法
    private func saveUserInfo(userAccount:LoopUserAccount){
        //得到的路径其实是一个数组,所以需要加上一个last
        //由于需要拼接文件路径,所以需要将路径转为NSString
        //使用默认转换的前提,被转换类型不能为可选类型
        
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: path)
    }
    
    //解档方法
    private func loadUserInfo()->LoopUserAccount?{
        
        let account = NSKeyedUnarchiver.unarchiveObject(withFile: path)
        
        //判断时候可以转换为LoopUserAccount类型,可以返回,否则返回一个空值
        if let userAccount = account as? LoopUserAccount{
            
            return userAccount
        }
        
        return nil
    }

    
    
    
}
